# -*- coding: utf-8 -*-
# import pretty_errors
import datetime
from loguru import logger


Weather_Info = main.GetInformation()

# 7天的天气数据
WeatherOf7DaysInfo = Weather_Info['data']

# 今日天气到6天后的天气信息
Day0Weather = Weather_Info['data'][0]
Day1Weather = Weather_Info['data'][1]
Day2Weather = Weather_Info['data'][2]
Day3Weather = Weather_Info['data'][3]
Day4Weather = Weather_Info['data'][4]
Day5Weather = Weather_Info['data'][5]
Day6Weather = Weather_Info['data'][6]


# 更新时间
def UpdateTime(weatherInfo):
    update_time = weatherInfo['update_time']
    return update_time


# 城市
def City(weatherInfo):
    city = weatherInfo['city']
    return city


# list 7天的最高温列表
def MaximumTemperatureDataList(weatherInfo):
    MTDL = [weatherInfo['data'][0]['tem1'][:-1],
            weatherInfo['data'][1]['tem1'][:-1],
            weatherInfo['data'][2]['tem1'][:-1],
            weatherInfo['data'][3]['tem1'][:-1],
            weatherInfo['data'][4]['tem1'][:-1],
            weatherInfo['data'][5]['tem1'][:-1],
            weatherInfo['data'][6]['tem1'][:-1]]
    # print("Handler.py 第57行，每天的最高温为：%s" % MTDL)
    return MTDL


# list 7天的低温列表
def MinimumTemperatureDataList(weatherInfo):
    mTDL = [weatherInfo['data'][0]['tem2'][:-1],
            weatherInfo['data'][1]['tem2'][:-1],
            weatherInfo['data'][2]['tem2'][:-1],
            weatherInfo['data'][3]['tem2'][:-1],
            weatherInfo['data'][4]['tem2'][:-1],
            weatherInfo['data'][5]['tem2'][:-1],
            weatherInfo['data'][6]['tem2'][:-1]]
    # print("Handler.py 第71行，每天的最低温为：%s" % mTDL)
    return mTDL


# list 7天的日期列表
def Date(weatherInfo):
    date = [weatherInfo['data'][0]['date'],
            weatherInfo['data'][1]['date'],
            weatherInfo['data'][2]['date'],
            weatherInfo['data'][3]['date'],
            weatherInfo['data'][4]['date'],
            weatherInfo['data'][5]['date'],
            weatherInfo['data'][6]['date']]
    return date


# list 7天的星期列表
def Day(weatherInfo):
    date = [weatherInfo['data'][0]['week'],
            weatherInfo['data'][1]['week'],
            weatherInfo['data'][2]['week'],
            weatherInfo['data'][3]['week'],
            weatherInfo['data'][4]['week'],
            weatherInfo['data'][5]['week'],
            weatherInfo['data'][6]['week']]
    return date


# 今日小时气温列表
def HoursTemperature(weatherInfo):
    hours_temperature = [weatherInfo['data'][0]['hours'],
                         weatherInfo['data'][1]['hours'],
                         weatherInfo['data'][2]['hours'],
                         weatherInfo['data'][3]['hours'],
                         weatherInfo['data'][4]['hours'],
                         weatherInfo['data'][5]['hours'],
                         weatherInfo['data'][6]['hours']]
    return hours_temperature


# [{'hours': '14时', 'wea': '多云', 'wea_img': 'yun', 'tem': '25', 'win': '北风', 'win_speed': '3-4级'}, {'hours': '15时',
def HoursInfo_PerDay_To_PerHours(weatherInfo):
    # 8项为一一个list的小时天气，共7天
    list_hours_Info = [weatherInfo['data'][0]['hours'],
                       weatherInfo['data'][1]['hours'],
                       weatherInfo['data'][2]['hours'],
                       weatherInfo['data'][3]['hours'],
                       weatherInfo['data'][4]['hours'],
                       weatherInfo['data'][5]['hours'],
                       weatherInfo['data'][6]['hours']]
    hours_Info_List = []
    for hours_Info_per_day in range(len(list_hours_Info)):
        per_day = list_hours_Info[hours_Info_per_day]
        for hours_Info_per_hours in range(len(per_day)):
            per_time = per_day[hours_Info_per_hours]
            hours_Info_List.append(per_time)
    return hours_Info_List


# [{'hours': '14时', 'wea': '多云', 'wea_img': 'yun', 'tem': '25', 'win': '北风', 'win_speed': '3-4级'}, {'hours': '15时',
# TODO:补全X轴缺失的时间
def HoursDate(weatherInfo):
    HoursInfo_List = HoursInfo_PerDay_To_PerHours(weatherInfo)
    # print("HoursInfo_List:%s" % HoursInfo_List)

    Number_Of_HoursInfo = len(HoursInfo_List)
    # print("Number_Of_HoursInfo:%s" % Number_Of_HoursInfo)

    # 当日年月日中的日
    today_number = UpdateTime(weatherInfo)[8:10]
    # 当日年月日中的月
    today_month_number = UpdateTime(weatherInfo)[5:7]

    hours_Info_month = []
    hours_Info_day = []
    hours_Info_time = []
    hours_Info_date = []
    hours_Info_weather = []
    hours_Info_temperature = []
    hours_Info_win = []
    hours_Info_win_speed = []
    for day in range(Number_Of_HoursInfo):
        # hours内"29日20时"的格式为HoursInfo_List[day]['day'].replace("时", ":00").replace("日", " ")
        the_day = HoursInfo_List[day]
        # the_day = HoursInfo_List[day]['day'][:-4]
        print(the_day)

        """
        # 与当天相差的天数
        the_difference_of_the_day = int(the_day) - int(today_number)
        # 【月】
        # 通过差异判断数据与当天的差异
        if the_difference_of_the_day >= 0:
            # hours_Info_day.append(the_difference_of_the_day)
            hours_Info_month.append(today_month_number)
        else:
            # 若当前为12月，后面天数要进位为1月
            month_number = int(today_month_number) + 1
            if month_number > 12:
                hours_Info_month.append("01")
            else:
                hours_Info_month.append(month_number)

        # 【日】
        hours_Info_day.append(the_day)
        # 【时】
        the_time = HoursInfo_List[day]['day'][3:-1]
        hours_Info_time.append(the_time)
        # 【date】
        the_date = '{}-{} {}:00'.format(hours_Info_month[day], hours_Info_day[day], hours_Info_time[day])
        hours_Info_date.append(the_date)

        # 【天气wea】
        the_weather = HoursInfo_List[day]['wea']
        hours_Info_weather.append(the_weather)

        # 【温度tem】
        the_temperature = HoursInfo_List[day]['tem'][:-1]
        hours_Info_temperature.append(the_temperature)

        # 【风向win】
        the_win = HoursInfo_List[day]['win']
        hours_Info_win.append(the_win)

        # 【风力等级win_speed】
        the_win_speed = HoursInfo_List[day]['win_speed']
        hours_Info_win_speed.append(the_win_speed)
    dict_HoursDate = dict()
    dict_HoursDate['HoursMonth'] = hours_Info_month
    dict_HoursDate['HoursDay'] = hours_Info_day
    dict_HoursDate['HoursTime'] = hours_Info_time
    dict_HoursDate['HoursDate'] = hours_Info_date
    dict_HoursDate['HoursWeather'] = hours_Info_weather
    dict_HoursDate['HoursTemperature'] = hours_Info_temperature
    dict_HoursDate['HoursWin'] = hours_Info_win
    dict_HoursDate['HoursWinSpeed'] = hours_Info_win_speed
    return dict_HoursDate
"""


print(HoursDate(Weather_Info))
"""
def ToCompleteEmptyDate(date):
    New_Date_List = []
    # 首个时间的的年份
    Year_Of_Now = str(datetime.datetime.now())[:4]
    # 首个时间的完整表达式
    Full_Date_Of_Now = datetime.datetime.strptime("-".join([Year_Of_Now, str(date[0])]), "%Y-%m-%d %H:%M")
    # print(Full_Date_Of_Now)
    for i in range(len(date)):
        # 时间差
        The_Date = (Full_Date_Of_Now + i * datetime.timedelta(hours=3)).strftime("%Y-%m-%d %H:%M:%S")[5:-3]
        New_Date_List.append(The_Date)
    return New_Date_List


# 补全从第四天开始数据量减半导致图像横向畸变
def MakeUpForTheMissing(data):
    New_data_List = []
    for Num in range(len(data)):
        if Num <= 24:
            New_data_List.append(data[Num])
        else:
            remainder = Num % 2
            # print("Num:%s" % Num)
            # print("remainder:%s" % remainder)
            # 从第26个数值（Num=25）开始，余数为1的是空缺位置
            # 第二重保险，若真的无法补偿时间，即写入""
            if remainder != 0:
                New_data_List.append(str(""))
                New_data_List.append(data[Num])
            else:
                New_data_List.append(str(""))
                New_data_List.append(data[Num])
    return New_data_List


# combine最低温
# TODO:在该曲线上增加一周最低温时间提示点
def MakeupMinimumTemperature(minimumTemperature, hoursTime):
    New_MinimumTemperature_List = []
    # 若第一个Hours_Info在08：00后，去除首个最低温数据，从Num=1开始，共6个数据
    if int(hoursTime[0]) > 8:
        # print("最低温的第一个数据没用，最低温的赋值从SequenceNum=1开始，共6个数据")
        SequenceNum = 1
        # 用Num遍历X坐标
        for Num in range(len(hoursTime)):
            # 早上08：00出现最低温。通过时间，筛选出出现最低气温对应的Num,将最低温度赋给New_MinimumTemperature_List
            if hoursTime[Num] == str("08"):
                # print("Num为 %s 的时候,出现一天最低温" % Num)

                New_MinimumTemperature_List.append(minimumTemperature[SequenceNum])
                SequenceNum = SequenceNum + 1
            # 非8：00，赋空值
            else:
                New_MinimumTemperature_List.append(str(""))
    # 若第一个Hours_Info在08：00及8：00前，7个最高温数据均有意义
    else:
        # print("最高温的第一个数据有用，最高温的赋值从SequenceNum=0开始，共7个数据")
        SequenceNum = 0
        # 用Num遍历X坐标
        for Num in range(len(hoursTime)):
            # 早上08：00出现最低温。通过时间，筛选出出现最低气温对应的Num,将最低温度赋给New_MinimumTemperature_List
            if hoursTime[Num] == str("08"):
                # 第一个最低温数据是第二天的数据，Num需要大于7才写入minimumTemperature[SequenceNum]，否则写入空数据
                if Num > 7:
                    # print("Num为 %s 的时候,出现一天最低温" % Num)
                    New_MinimumTemperature_List.append(minimumTemperature[SequenceNum])
                    SequenceNum = SequenceNum + 1
                else:
                    # TODO:每天早上8点前更新一次最低温数据并写入以"年-月-日 时"为格式命名的TXT中，供每次读取
                    New_MinimumTemperature_List.append("")

            # 非8：00不在在低温写入空值，赋空值
            else:
                New_MinimumTemperature_List.append(str(""))
    return New_MinimumTemperature_List


# combine最高温
# TODO:在该曲线上增加一周最高温时间提示点
def MakeupMaximumTemperature(MaximumTemperature, hoursTime):
    New_MaximumTemperature_List = []
    # ！！若第一个Hours_Info在14：00后，去除首个最高温数据，从Num=1开始，共6个数据
    if int(hoursTime[0]) > 14:
        # print("最高温的第一个数据没用，最高温的赋值从SequenceNum=1开始，共6个数据")
        SequenceNum = 1
        # 用Num遍历X坐标
        for Num in range(len(hoursTime)):
            # print("Num:%s" % Num)
            # 14：00出现最高温。通过时间，筛选出出现最高气温对应的Num,将最高温度赋给New_MaximumTemperature_List
            if hoursTime[Num] == str("14"):
                # print("hoursTime[Num] == str(14)成立，hoursTime[Num]:%s" % hoursTime[Num])
                # !!第一个最高温数据是第一天的数据，Num需要小于7就要写入MaximumTemperature[SequenceNum]，否则写入空数据
                if Num <= 5:
                    # print("Num <= 7成立，最高温已无意义，空值入栈")
                    # TODO:每天14点前更新一次最高温数据并写入以"年-月-日 时"为格式命名的TXT中，供每次读区
                    New_MaximumTemperature_List.append("")

                else:
                    # print("Num > 7成立，Num为 %s 的时候,出现一天最高温:%s" % (Num, MaximumTemperature[SequenceNum]))
                    New_MaximumTemperature_List.append(MaximumTemperature[SequenceNum])
                    SequenceNum = SequenceNum + 1

            # 非14：00，赋空值
            else:
                # print("hoursTime[Num] ！= str(14)，空值入栈")
                New_MaximumTemperature_List.append(str(""))
    # ！！若第一个Hours_Info在12：00及12：00前，7个最高温数据均有意义
    else:
        # print("最高温的第一个数据有用，最高温的赋值从SequenceNum=0开始，共7个数据")
        SequenceNum = 0
        # 用Num遍历X坐标
        for Num in range(len(hoursTime)):

            # 14：00出现最高温。通过时间，筛选出出现最低气温对应的Num,将最高温度赋给New_MaximumTemperature_List
            if hoursTime[Num] == str("14"):
                # print("Num为 %s 的时候,出现一天最高温" % Num)

                New_MaximumTemperature_List.append(MaximumTemperature[SequenceNum])
                SequenceNum = SequenceNum + 1

            # 非14：00，赋空值
            else:
                New_MaximumTemperature_List.append(str(""))
    # print(New_MaximumTemperature_List)
    return New_MaximumTemperature_List


# eg.2021-01-29 08:00:00 => 周五
def DateToWeekDay(date):
    week_day_dict = {
        0: '周一',
        1: '周二',
        2: '周三',
        3: '周四',
        4: '周五',
        5: '周六',
        6: '周日',
    }
    week_day = week_day_dict[datetime.datetime.strptime(date, "%m-%d %H:%M").weekday()]
    return week_day


# MarkLine的X轴数据及WeekDay valve
def SplitLineAndWeekday(weatherInfo):
    MarkLineList = []
    WeekDayList = []
    TheList = ToCompleteEmptyDate(MakeUpForTheMissing(HoursDate(weatherInfo)['HoursDate']))
    print("TheList:%s" % TheList)
    for day in range(len(TheList)):
        RightTime = TheList[day][6:8]
        if RightTime == "02" or "02" == RightTime:
            # MarkLineList用于储存MarkLine的数据
            MarkLineList.append(TheList[day])
            # WeekDayList用于储存提醒日期的数据
            WeekDayList.append("".join([DateToWeekDay(TheList[day]), " ", TheList[day][:5]]))
    return MarkLineList, WeekDayList


def handle(weatherInfo):
    Dictinfo = dict()
    Dictinfo['UpdateTime'] = UpdateTime(weatherInfo)
    Dictinfo['City'] = City(weatherInfo)
    Dictinfo['day'] = Day(weatherInfo)

    Dictinfo['date'] = Date(weatherInfo)
    # 以下数据需要补全从第四天开始数据量减半导致图形横向畸变
    # Dictinfo['HoursMonth'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursMonth'])
    # Dictinfo['HoursDay'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursDay'])
    # Dictinfo['HoursTime'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursTime'])
    Dictinfo['HoursDate'] = ToCompleteEmptyDate(MakeUpForTheMissing(HoursDate(weatherInfo)['HoursDate']))

    Dictinfo['HoursWeather'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursWeather'])
    Dictinfo['HoursTemperature'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursTemperature'])
    Dictinfo['HoursWin'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursWin'])
    Dictinfo['HoursWinSpeed'] = MakeUpForTheMissing(HoursDate(weatherInfo)['HoursWinSpeed'])

    # 低温高温数据

    Dictinfo['MinimumTemperature'] = MakeupMinimumTemperature(MinimumTemperatureDataList(weatherInfo),
                                                              MakeUpForTheMissing(HoursDate(weatherInfo)['HoursTime']))

    Dictinfo['MaximumTemperature'] = MakeupMaximumTemperature(MaximumTemperatureDataList(weatherInfo),
                                                              MakeUpForTheMissing(HoursDate(weatherInfo)['HoursTime']))
    Dictinfo['MarkLine'], Dictinfo['Weekday'] = SplitLineAndWeekday(weatherInfo)
    return Dictinfo


if __name__ == '__main__':
    # HoursDate(Weather_Info)
    # print(handle(Weather_Info))
    logger.info(UpdateTime(Weather_Info))


    # print(handle(BInfo)['HoursDate'])
    # print(handle(BInfo)['HoursDay'])
    # print(handle(BInfo)['HoursTime'])
    # print("====================")
    # print(handle(BInfo)['HoursDate'])
    # print(handle(BInfo)['HoursWeather'])
    # print(handle(BInfo)['HoursTemperature'])
    # print(handle(BInfo)['HoursWin'])
    # print(handle(BInfo)['HoursWinSpeed'])
    # print(SplitLineAndWeekday(BInfo))

    # BInfoprint(handle(BInfo)['MarkLine'])
    # print(handle(BInfo)['Weekday'])
    #
    # def SplitLineAndWeekday(weatherInfo):
    #     MarkLineList = []
    #     WeekDayList = []
    #     TheList = handle(weatherInfo)['HoursDate']
    #     for day in range(len(TheList)):
    #         RightTime = TheList[day][6:8]
    #         if RightTime == "02" or "02" == RightTime:
    #             # MarkLineList用于储存MarkLine的数据
    #             MarkLineList.append(TheList[day])
    #             # WeekDayList用于储存提醒日期的数据
    #             WeekDayList.append("".join([DateToWeekDay(TheList[day]), " ", TheList[day][:5]]))
    #     return MarkLineList, WeekDayList
    #
    # a, b = SplitLineAndWeekday(BInfo)
    # print(SplitLineAndWeekday(BInfo))
"""
